var express = require('express'),
    sha1 = require('node-sha1'),
    swig = require('swig-templates'),
    router = express.Router(),
    request = require('request');

var disableWechat = process.env.disable_wechat;

var wx = {
    verify: function(req, res, callback) {
        if (disableWechat) {
            callback();
            return;
        }

        if (req.cookies.user_id) {
            if(callback) callback();
        } else {
            res.redirect("/");
        }
    },
    goLogin: function(req, res) {
        if (disableWechat) {
            callback();
            return;
        }

        var url="http://wechat.zfpresent.com";
        res.redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ config.appid +"&redirect_uri="+ encodeURIComponent(url) +"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
    },
    getGetticket: function(req, callback) {
        if (disableWechat) {
            callback();
            return;
        }

        var nowDate = new Date().getTime();
        if (config.getticket && nowDate > config.getticket.maxAge) {
            config.getticketReques = false;
        }        
        if (config.getticketReques != true) {
            config.getticketReques = true;
            config.getticket = null;
            request.get({
                url: "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ config.serveToken.access_token +"&type=jsapi"
            }, function (error, response, body) {
                var bodyData = {
                    noncestr: config.appid + "hvs" + Math.ceil(Math.random() * 100000),
                    timestamp: new Date().getTime()
                };
                try {
                    var data = JSON.parse(body),
                        date = new Date();
                    data.maxAge = date.setSeconds(date.getSeconds() + data.expires_in);
                    for (var i in data) {
                        bodyData[i] = data[i];
                    }
                    bodyData.ticketStr = "jsapi_ticket=" + bodyData.ticket + "&noncestr=" + bodyData.noncestr + "&timestamp=" + bodyData.timestamp + "&url=";
                    bodyData.appid = config.appid;
                    config.getticket = JSON.parse(JSON.stringify(bodyData));
                } catch (e) {
                    config.getticketReques = false;
                    bodyData = {
                        errcode: 400
                    };
                }
                if (callback) callback(bodyData);
            });
        } else if (config.getticketReques && !config.getticket) {
            var invtTime = setInterval(function () {
                if (config.getticket) {
                    if (callback) callback();
                    clearInterval(invtTime);
                }
            }, 100);
        } else {
            if (callback) callback();
        }
    },
    getToken: function (req, callback, gocallback) {
        if (disableWechat) {
            callback();
            return;
        }

        var nowDate = new Date().getTime();
        if (config.serveToken && nowDate > config.serveToken.maxAge) {
            config.serveTokenReques = false;
        }
        if (config.serveTokenReques != true) {
            config.serveTokenReques = true;
            config.serveToken = null;
            request.get({
                url: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + config.appid + "&secret=" + config.secret
            }, function (error, response, body) {
                try {
                    var data = JSON.parse(body);
                    if (data.access_token) {
                        var date = new Date();
                        data.maxAge = date.setSeconds(date.getSeconds() + data.expires_in);
                        config.serveToken = data;
                    } else {
                        config.serveTokenReques = false;
                    }
                } catch (e) {
                    config.serveTokenReques = false;
                }

                if (gocallback) gocallback();
                wx.getGetticket(req, function () {
                    if (callback) callback();
                });
            });
        } else if (config.serveTokenReques && !config.serveToken) {
            var invtTime = setInterval(function () {
                if (config.serveToken) {
                    wx.getGetticket(req, function () {
                        if (callback) callback();
                    });

                    if (gocallback) gocallback();
                    clearInterval(invtTime);
                }
            }, 100);
        } else {
            if (gocallback) gocallback();
            wx.getGetticket(req, function () {
                if (callback) callback();
            });
        }
    },
    getUser:function (req, res, callback) {
        if (disableWechat) {
            callback();
            return;
        }

        var me = this;
        // try {
            request.get({
                url: "https://api.weixin.qq.com/sns/userinfo?access_token=" + req.session.tokenData.access_token + "&openid=" + req.session.tokenData.openid + "&lang=zh_CN "
            }, function (error, response, body) {
                var data = JSON.parse(body);
                req.session.wxUser = data;
                request.post({
                    url: config.resourcePath.apiRoot + "/index/index/wechat",
                    formData: {
                        openid: data.openid,
                        nickname: data.nickname,
                        headimgurl: data.headimgurl,
                        sex: data.sex
                    }
                }, function (usererror, userresponse, userbody) {
                    var userData = JSON.parse(userbody);
                    req.session.user = userData;
                    if (userData && userData.message) {
                        res.cookie('user_id', userData.message.user_id, {
                            maxAge: config.cookieTime,
                            httpOnly: false
                        });
                    }
                    if (typeof callback == 'function') {
                        callback({
                            code: 200,
                            data: userData
                        });
                    }
                });
            });
        // } catch (e) {
        //     if (typeof callback == 'function') {
        //         callback({
        //             code: 201
        //         })
        //     }
        // }
    },
    getAccessToken:function (req, res, url, callback) {
        if (disableWechat) {
            callback();
            return;
        }

        var me = this;
        try {
            request.get({
                url: url
            }, function (error, response, body) {
                var data = JSON.parse(body);
                // code过期重新验证
                if (data.access_token) {
                    var date = new Date();
                    data.maxAge = date.setSeconds(date.getSeconds() + data.expires_in);
                    req.session.tokenData = data;
                    me.getUser(req, res, callback);
                } else {
                    req.session.wxCode = '';
                    wx.goLogin(req, res);
                }
            });
        }catch (e){
            if (typeof callback=='function') {
                callback({
                    code:201
                })
            }
        }
    },
    goAccessToken: function(req, res, callback) {
        if (disableWechat) {
            callback();
            return;
        }

        var me = this,
            nowDate = new Date().getTime();
        try {
            if (req.cookies.user_id && parseInt(req.cookies.user_id) > 0) {
                if ('function' == typeof callback) {
                    callback({
                        code: 200,
                        data: req.session.wxUser
                    });
                }
            } else if (req.query.code || req.session.wxCode) {
                if (!req.session.wxCode) {
                    req.session.wxCode = req.query.code;
                }
                // 刷新token
                if (req.session.tokenData) {
                    if (nowDate > req.session.tokenData.maxAge) {
                        var link = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + config.appid + "&grant_type=refresh_token&refresh_token=" + req.session.tokenData.refresh_token;
                        me.getAccessToken(req, res, link, callback);
                    } else {
                        me.getUser(req, res, callback);
                    }
                } else {
                    // 用户第一次进去应用创建token
                    var link = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + config.appid + "&secret=" + config.secret + "&code=" + req.session.wxCode + "&grant_type=authorization_code";
                    me.getAccessToken(req, res, link, callback);
                }
            } else {
                wx.goLogin(req, res);
            }
        }catch(e) {
            if ('function' == typeof callback) {
                callback({
                    code: 201
                })
            }
        }
    }
}

module.exports = wx;
